home
clear;
task=mfilename;
LoadPsychHID;
KbQueueCreate();

close all
clear persistent
clear global
%clear mex
BUTTONEVENT=25;
%%
InitializeDummy=false;
if Eyelink('Initialize', 'PsychEyelinkDispatchCallback')
    InitializeDummy=questdlg_offscreen('Eyelink is not properly connected. Initialize in Dummy mode?', ...
        'Eyelink is not connected!', ...
        'Yes','Quit','Yes');
    if strcmp(InitializeDummy,'Yes')
        InitializeDummy=true;
        if Eyelink('InitializeDummy', 'PsychEyelinkDispatchCallback')
            fprintf('InitializeDummy failed too\n')
            return;
        end
    else
        fprintf('cancled by user\n')
        return;
    end
end
%Eyelink('command',sprintf('clear_screen %d',0));
%%
fprintf('\nSTART\n')
c=define_colors(uint8(256));
c.BACKGROUND=c.BLACK;
c.GO=c.GREEN;
c.NG=c.RED;
c.TTEXT=c.WHITE;
ec = EL_colors;
ec.BACKGROUND=ec.BLACK;
ec.GO=ec.GREEN;
ec.NG=ec.RED;
ec.TTEXT=ec.L_GREY;

edf_name='edf_name';
%old
screenRect=get(0,'ScreenSize');
screenpixW=screenRect(3);
screenpixH=screenRect(4);
%new
MonitorPositions=get(0,'MonitorPositions');
screenpixW=MonitorPositions(end,3);
screenpixH=MonitorPositions(end,4);
%        screenpixW=1280;
%        screenpixH=1024;
c_x=round(double(screenpixW/2)); % the stupid text commands require a double for pixels placement
c_y=round(double(screenpixH/2));
%whichScreen = max(Screen('Screens'));
if size(MonitorPositions,1)==1
    screennum=0;
else
    screennum=2;
end

%% computer
temp=pwd;
basefolder=temp(1:strfind(temp,'bcoe')+4);
if isempty(basefolder);
    shit;
    crash;
end
home_folder=[basefolder 'data\button\'];
home_folder=sprintf('%s%s',home_folder,task);
if isdir(home_folder)==0
    mkdir(home_folder)
end

if screenpixW==1920
    distance2screen=600*0.0393700787;% mm 2 inches
    screenwidth=310*0.0393700787;  % mm 2 inches
    sheightinches=174*0.0393700787;% mm 2 inches
    
else %screenpixW== 1280
    distance2screen=500*0.0393700787;% mm 2 inches
    screenwidth=341*0.0393700787;  % mm 2 inches
    sheightinches=270*0.0393700787;% mm 2 inches
end
dphs = atan2(screenwidth/2,distance2screen)*180/pi;%degrees per half screen
ppd = (screenpixW)/2/dphs; %pixels/degree
uimenufcn(0,'WindowCommandWindow');
drawnow;

try
    %% Screen
    %KbQueueCreate();
    KbQueueStart();
    Screen('Preference','SkipSyncTests',1);
    Screen ('Preference','VisualDebugLevel',3);
    Screen('Preference','SuppressAllWarnings',1);
    %ListenChar(0);%turn off character listening and reset the buffer which holds the captured characters.
    %ListenChar(2);%enable listening, additionally any output of keypresses to Matlab windows is suppressed.
    [w, wRect]=Screen('OpenWindow', screennum, 0,[],32,2);
    Screen(w,'BlendFunction',GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    pause(.01);
    Screen('fillrect',w,c.BACKGROUND);
    Screen('flip',w);
    
    Screen('TextStyle',w,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
    Screen('TextFont',w,'Tahoma');
    Screen('TextSize',w,40);
    ttext='Hit the space bar to continue';
    DrawFormattedText(w,ttext,'center',(c_y)-100,(c.TTEXT));
    Screen('flip',w);
    fprintf('%s\n',ttext)
    keyIsDown=0;
    keyCode=0;
    lastkeyCode=0;
    lastbutton=0;
    
    %ListenChar(2);
    % Disable character forwarding to console:
    %        PsychHID('KeyboardHelper', -12);
    % Enable character forwarding to the runtime/console.
    %       PsychHID('KeyboardHelper', -10);
    ii=0;
    
    while keyCode~=32% SPACE on pcwin
        %     [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
        %     if keyIsDown
        %         keyCode=max([0,find(keyCode,1)]);
        [keyPress, keyCodes,keyTimes]= Kb_bcoe();
        if keyPress
            keyCode=keyCodes(1);
            keyTime=keyTimes(1);
            if keyCode==27 % esc key
                ttext='Task Aborted';
                DrawFormattedText(w,ttext,'center','center',c.ORANGE);
                Screen('flip',w);
                fprintf('%s\n',ttext);
                pause(1);
                Screen('Closeall');
                KbQueueRelease();
                return
                %else
                %FlushEvents;
            end
        end
        ii=ii+1;
        if ii>1000000
            ttext='timed out';
            DrawFormattedText(w,ttext,'center','center',c.ORANGE);
            Screen('flip',w);
            fprintf('%s\n',ttext);
            pause(1);
            Screen('Closeall');
            KbQueueRelease();
            return
        end
    end
    keyCode=0;
    fprintf('it worked\n')
    Screen('flip',w);
    %
    %% Eyelink redo again after clearing all MEX
    %el = EyelinkInitDefaults_bcoe(w); %el=elglobal; %make it local and usable
    el = EyelinkInitDefaults(w);%el=elglobal; %make it local and usable
    %their default is the inverse of this:
    el.backgroundcolour = c.BLACK(1);% bcoe
    el.foregroundcolour = c.WHITE(1);% bcoe
    el.msgfontcolour    = c.M_GREY(1);% bcoe
    el.imgtitlecolour   = c.M_GREY(1);% bcoe
    el.calibrationtargetcolour=el.foregroundcolour;
    %el.eyeimgsize=screenpixW/20+10;
    %el.msgfont='Tahoma';
    el.msgfontsize=12;
    %el.imgtitlefont='Tahoma';
    el.imgtitlefontsize=12;
    EyelinkUpdateDefaults(el); % need to update it on the host
    
    % make sure that we get gaze data from the Eyelink
    Eyelink('Command','calibration_type = HV5');
    %first events
    Eyelink('Command','file_event_filter = LEFT,RIGHT, AREA, GAZE, SACCADE, FIXATION, BLINK, MESSAGE, BUTTON, INPUT');%sets which events will be written to the EDF file.
    Eyelink('Command','link_event_filter = LEFT,RIGHT, AREA, GAZE, SACCADE, FIXATION, BLINK, MESSAGE, BUTTON, INPUT');%sets which types of events will be sent through link
    %then samples
    status=Eyelink('command','link_sample_data = LEFT,RIGHT,GAZE,AREA,GAZERES,HREF,PUPIL,STATUS,INPUT,BUTTON');
    if status~=0
        disp('link_sample_data error')
    end
    status=Eyelink('command','file_sample_data = LEFT,RIGHT,GAZE,AREA,GAZERES,HREF,PUPIL,STATUS,INPUT,BUTTON');
    if status~=0
        disp('file_sample_data error')
    end
    
    status=Eyelink('command','inputword_is_window = ON');
    if status~=0
        disp('inputword_is_window error')
    end
    openfile = Eyelink('openfile',[edf_name,'.edf']);
    if openfile~=0
        disp(['Cannot create EDF file: ' edf_name]);
        ttext='Task Aborted';
        DrawFormattedText(w,ttext,'center','center',c.ORANGE);
        Screen('flip',w);
        fprintf('%s\n',ttext);
        Eyelink('setofflinemode');
        Eyelink('shutdown');
        pause(1);
        Screen('Closeall');
        KbQueueRelease();
        ListenChar(0);
        return;
    end
    %clear openfile
    Eyelink('command', 'add_file_preamble_text = Recorded by BCOE');
    %%
    %     if Eyelink('isconnected')~= -1
    %         el.callback = '';
    %         fprintf(' entered EyelinkDoTrackerSetup\n')
    %         EyelinkDoTrackerSetup(el);
    %         %EyelinkDoTrackerSetup(el, el.ENTER_KEY);
    %         fprintf('  exited EyelinkDoTrackerSetup\n')
    %         eye_used = Eyelink('EyeAvailable'); % get eye that's tracked
    %         if eye_used == el.BINOCULAR; % if both eyes are tracked
    %             eye_used = el.LEFT_EYE; % use left eye
    %         end
    %     end
    %%
    Eyelink('StartRecording'); % messages must be AFTER startrecording and require SPRINTF to convert floats to strings
    
    SetMouse(c_x*3,c_y);
    lastkeyCode=0;% anti hammering
    abs_start_time=getsecs;
    gogogo=true;
    KbQueueFlush();
    Eyelink('message','SYNCTIME'); % old????
    Eyelink('message','RETRACE_INTERVAL: 16.667')
    Eyelink('message',sprintf('disttoscreen %0.2f sheightinches %0.2f swidthinches %0.2f PPD %0.2f screenpixW %0.0f screenpixH %0.0f',distance2screen,sheightinches,screenwidth,ppd,screenpixW,screenpixH));
    Eyelink('message',sprintf('abs_start_time: %f',abs_start_time));% requires SPRINTF
    %fprintf('disttoscreen %f sheightinches %f swidthinches %f PPD %f ',distance2screen,sheightinches,screenwidth,ppd);
    Eyelink_start_time = Eyelink('TrackerTime');
    %change_state_time(index,:)=[single(state) 0];
    Screen('flip',w);
    fprintf('start recording\n')
    
    while gogogo==true
        [keyPress, keyCodes, keyTimes]= Kb_bcoe(abs_start_time);
        if keyPress
            if keyCodes(1)==27
                disp('escaped!')
                gogogo=false;
            else
                if keyCodes(1)==32
                    DrawFormattedText(w,'','center','center',c.ORANGE);
                else
                    DrawFormattedText(w,num2str(keyCodes(1)),'center','center',c.ORANGE);
                end
                Screen('flip',w);                
            end
        end
        [samplesIn, eventsIn, drained] = Eyelink('GetQueuedData');%, eye_used);
        if ~isempty(eventsIn),
            if any(eventsIn(2,:)==BUTTONEVENT)
                timestamp = eventsIn(1,eventsIn(2,:)==BUTTONEVENT);
                keyPressed = eventsIn(3,eventsIn(2,:)==BUTTONEVENT);
                DrawFormattedText(w,num2str(keyPressed),'center','center',c.ORANGE);
            else
                fprintf('something: %d!!!\n',eventsIn(2,:))                
            end
            Screen('flip',w);
            
        end
        
    end %while gogogo==true
    Eyelink('stoprecording');
    Eyelink('closefile');
    Eyelink('command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)-60,ec.BLUE,'thank you!'));
    Eyelink('command',sprintf('draw_text %d %d %d %s ',round(c_x),round(c_y)+60,ec.BLUE,'please rest.'));
    
    % fade to grey
    Screen('TextSize',w,58);
    ctemp=(c.M_GREY-c.BACKGROUND)./80;
    for i = 1:80 % fade to ?_GREY algorythm
        Screen('fillrect',w,round(c.BACKGROUND+(ctemp*i)));
        DrawFormattedText(w,'thank you!','center',c_y-60,c.BLUE);
        DrawFormattedText(w,'please rest.','center',c_y+60,c.BLUE);
        Screen('flip',w);
    end
    %%
    Eyelink('StopRecording');
    clear ctemp
    Screen('CloseAll')
    KbQueueRelease();
    ListenChar(0);
    fprintf('stop recording\n')
    ShowCursor
    Eyelink('command',sprintf('clear_screen %d',0));
    Eyelink('shutdown');
catch badness
    badness.message
    badness.stack
    shit
end

